package org.example.springnetty.MyNetty.echo;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.util.concurrent.atomic.AtomicInteger;

public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
    private AtomicInteger count = new AtomicInteger(0);

    // 读取到网络数据后做业务处理,并关闭连接
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf byteBuf) throws Exception {
        System.out.println("client accept :"+byteBuf.toString(CharsetUtil.UTF_8)+"---"+"And the counter is "+count.incrementAndGet());
//        ctx.close();
    }

    // Channel活跃后做业务处理
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
//        ctx.writeAndFlush(Unpooled.copiedBuffer(
//                "Hello Netty", CharsetUtil.UTF_8));
        String request = "Mark,Zhuge,Fox,Zhouyu,loulan"+ System.lineSeparator();
        final ByteBufAllocator alloc = ctx.alloc();
        ByteBuf msg = null;
        for (int i = 0; i < 100; i++) {
            msg = alloc.buffer(request.length());
            ByteBuf byteBuf = alloc.buffer();
            msg.writeBytes(request.getBytes());
            ctx.writeAndFlush(msg);
        }
    }
}
